import { Component, Vue, Prop, Watch } from "@some21/vue-class-decorator";
import * as echarts from "echarts";
// import { debounce } from "lodash";

@Component({
  name: "ChartBase",
})
export default class extends Vue {
  loading = true;
  chart: echarts.ECharts;
  options: echarts.EChartsOption = {};

  @Prop({ type: String, default: "100%" })
  width: string;
  @Prop({ type: String, default: "100%" })
  height: string;

  @Watch("width")
  @Watch("height")
  onSizeChange() {
    this.chart?.resize();
  }

  mounted() {
    this.chart = echarts.init(this.$el as HTMLDivElement, "macarons");
    const ifmElm = document.createElement("iframe");
    ifmElm.setAttribute("seamless", "seamless");
    ifmElm.style.cssText =
      "top:0;left:0;height:1px;width:100%;position:absolute;z-index:-1;border:none;box-sizing:border-box;visibility:hidden;opacity:0;pointer-events:none";
    ifmElm.onload = evt => {
      // const onWidthChange = debounce(() => this.chart?.resize(), 50);

      ((evt.target as any).contentWindow as Window).onresize = () => {
        this.chart?.resize();
      };
    };
    this.$el.appendChild(ifmElm);
    this.chart.setOption(this.options);
    this.loading = false;
  }

  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.clear();
    this.chart.dispose();
    this.chart = null;
  }

  protected render(h: import("vue").CreateElement) {
    // [<div class="chart" style={{ height: this.height, width: this.width }} vLoading={this.loading}></div>];
    return h("div", {
      staticStyle: { boxSizing: "border-box", overflow: "hidden", position: "relative", height: this.height, width: this.width },
      directives: [{ name: "loading", value: this.loading }],
    });
  }
}
